package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ScrollView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import artid.com.arttogo.R;
import artid.com.arttogo.adapter.AuthenticationAdapter;
import artid.com.arttogo.bean.CelebritySealInfoParser;
import artid.com.arttogo.bean.InstitutionArtLits;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.fragment.BaseFragment;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.utils.VeDate;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableScrollView;
import artid.com.arttogo.view.xlistview.PLA_AbsListView;
import artid.com.arttogo.view.xlistview.PLA_AdapterView;
import artid.com.arttogo.view.xlistview.XListView;

/**
 *
 * 类名称：OrganizationDynActivity
 * 类描述：机构作品
 * 创建时间：2017/4/27 15:35
 *
 */
public class OrganizationDynActivity extends BaseFragment implements View.OnClickListener, XListView.IXListViewListener {
	private View mView;
	private Context mContext;
	private boolean isRefreshed = false;// 是否刷新
	private int page = 1;
	private XListView mListView;
	private String imgwide;// 请求的图片宽度
	private Boolean isOpen = false;//判断介绍是否展开
	private int dataNum;//数据总条数
	private int requestDataNum=20;//请求数据数量
	private Boolean isLoad=true;//是否加载数据（默认可以加载）
	private AuthenticationAdapter mAdapter;
	private List<InstitutionArtLits> list=new ArrayList<>();
	private List<InstitutionArtLits> more_list=new ArrayList<>();
	private String InstitutionsId;//结构ID
	private ArrayList<String> ids;//传递的作品ID集合实现左右滑动

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.activity_organization_dyn, null);
		mContext = getActivity();
		initView();
		return mView;
	}

	private void initView(){
		InstitutionsId=getActivity().getIntent().getExtras().getString("id");
		imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 2) + "";
		mListView = (XListView) mView.findViewById(R.id.OrganizationDyn_listView);
		mListView.setPullRefreshEnable(false);
		mListView.setPullLoadEnable(false);
		mListView.setXListViewListener(this);
		mListView.setOnScrollListener(scrollListener);
		mListView.setOnItemClickListener(onItenClick);
		getData(true);
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		// 下拉刷新
		page = 1;
		isRefreshed = true;
		getData(false);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		// 上拉加载
		page++;
		getData(false);
	}

	@Override
	public void onClick(View v) {

	}

	/**
	 * Item点击事件
	 */
	PLA_AbsListView.OnItemClickListener onItenClick=new PLA_AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
			ids=new ArrayList<>();
			for (int i = 0; i < more_list.size(); i++) {
				ids.add(more_list.get(i).getArt_id());
			}
			Intent intent = new Intent(mContext, CollectionDetailPagerActivity.class);
			intent.putExtra("isOrg", true);
			// 得到新加的item，加入原来的json
			intent.putStringArrayListExtra("id", ids);
			intent.putExtra("index", position);
			intent.putExtra("titleName", more_list.get(position).getArttitle());
			startActivity(intent);
		}
	};

	/**
	 * 瀑布流滑动事件
	 */
	PLA_AbsListView.OnScrollListener scrollListener=new PLA_AbsListView.OnScrollListener() {
		@Override
		public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

		}

		@Override
		public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			Log.d("log","滑动："+firstVisibleItem+"====="+(requestDataNum-11));
			if(more_list.size()!=dataNum && isLoad==true){
				//-11是数据已经显示一半的时候如果加头了就-12
				//-12是数据已经显示一半的时候（因为是瀑布流并且加了头所以-12）
				if(page==1 && firstVisibleItem==(requestDataNum-11)){
					page++;
					getData(false);
				}else if(((page*requestDataNum)-11)==firstVisibleItem){
					page++;
					getData(false);
				}
			}
		}
	};

	/**
	 * 获取机构作品数据
	 */
	private void getData(Boolean isLoadDialog) {
		isLoad=false;
		if(isLoadDialog){
			VolleyBasic.showLoding(mContext);
		}
		VolleyBasic.getInstanceNoDialog(getActivity()).post(
				Cache.institutionArtLits, VolleyMap.getInstance().institutionArtLits(InstitutionsId,imgwide,page,requestDataNum),
				InstitutionArtLits.class, new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						isLoad=true;//如果加分页了释放改为true
						// TODO Auto-generated method stub
						if (isRefreshed) {
							mListView.stopRefresh();
						} else {
							mListView.stopLoadMore();
						}
						JSONObject jsonString = vd.getObj();
						JSONArray jsonArray = jsonString.optJSONArray("data");
						list = (List<InstitutionArtLits>) vd.getList();
						if (list != null) {
							if (page == 1) {
								try {
									JSONObject jsonObject = new JSONObject(vd.getJson());
									dataNum = jsonObject.getInt("num");
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
							if (isRefreshed == true) {
								more_list.clear();
								isRefreshed = false;
							}
							if (!list.isEmpty()) {
								more_list.addAll(list);
							}

							if (more_list.size() == 0) {
								mListView.setPullLoadEnable(false);
							} else {
								mListView.setPullLoadEnable(true);
							}
							if (mAdapter == null) {
								mAdapter = new AuthenticationAdapter(mContext, more_list);
								mListView.setAdapter(mAdapter);

							}
							mAdapter.notifyDataSetChanged();
						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						isLoad=true;
						if (isRefreshed) {
							mListView.stopRefresh();
						} else {
							mListView.stopLoadMore();
						}
					}
				});
	}
}
